#include <QSqlQuery>
#include <QMap>
#include <QPluginLoader>
#include <QSqlDriverPlugin>
#include <QSqlError>
#include <QDebug>

#include "arsadapter.h"

////////// ARSAdapter //////////////////////////////////////////////////////////////////////////////

ARSAdapter::ARSAdapter(QObject * parent)
    : QObject(parent)
{

}

QString ARSAdapter::name() const
{
    return "arsadapter";
}

QString ARSAdapter::description() const
{
    return tr("This plugin provides access to ARS database");
}

bool ARSAdapter::connectToDatabase(const QString & host, int port, const QString & dbName,
                                   const QString & login, const QString & password)
{
    QPluginLoader loader("c:\\QtSDK\\Desktop\\Qt\\4.7.3\\mingw\\plugins\\sqldrivers\\qsqlocid4.dll");
    QObject *plugin = loader.instance();

    if (!plugin)
        return false;

    QSqlDriverPlugin *sqlPlugin  = qobject_cast<QSqlDriverPlugin *>(plugin);

    if (!sqlPlugin ) {
        qDebug() << "SQL plugin loading failed";
        return false;
    }

    m_db = QSqlDatabase::addDatabase(sqlPlugin->create("QOCI"));
    m_db.setHostName(host);
    m_db.setPort(port);
    m_db.setDatabaseName(dbName);
    if(!m_db.open(login, password))
    {
        qDebug("Cannot connect to database. ");
        qDebug() << m_db.lastError().text();
        return false;
    }

    return true;
}

ServerModel * ARSAdapter::createModel()
{
    ServerModel * model = new ServerModel(this);
    if(!m_db.isOpen())
        return 0;

    QSqlQuery query = m_db.exec("SELECT f.NAME as name," \
                 "f.TIMESTAMP as createDate," \
                 "NULL as modifiedDate," \
                 "f.OWNER as createdBy," \
                 "f.LASTCHANGED as modifiedBy,"\
                 "NULL as changeHistory,"\
                 "NULL as helpText FROM filter f, filter_mapping fm "\
                 "WHERE f.filterid = fm.filterid AND fm.schemaid = 9");

    if(!query.isActive())
    {
        qDebug() << "Cannot retrieve model from ARS server. " << query.lastError().text();
        return 0;
    }

    while(query.next())
    {
        ARSFilter * object = new ARSFilter(model);
        object->setName(query.value(0).toString());
        model->addWorkflowObject(object);
    }

    return model;
}

ARSExpr * ARSAdapter::parseExpr(const QString expr, QObject * parent)
{
    return 0;
}

////////////////////////////////////////////////////////////////////////////////////////////////////

//Q_EXPORT_PLUGIN2(arsadapter, ARSAdapter)

////////////////////////////////////////////////////////////////////////////////////////////////////
